const fs = require("fs");
const path = require("path");
const http = require("http");
const https = require("https");
const url = require("url");
const randomstring = require("randomstring");
const axios = require("axios").default;
const Debug = require("debug");

const dbg = Debug("Ya-HTTP-write");
dbg.enabled = true;

const oauthmanage = require("./../oauthmanage");
const TOKEN = oauthmanage.getToken() || process.env['DEBUGTOKEN']
dbg("TOKEN is ", TOKEN);
const mntpath = path.join(__dirname, "../../..", "mnt");
dbg("mnt-path is ", mntpath);



axios.get(`https://cloud-api.yandex.net/v1/disk/resources/upload?path=${encodeURIComponent(
    `app:/write.${randomstring.generate(5)}.msi.bin`
)}`, {
        headers: {
            Authorization: `OAuth ${TOKEN}`
        }
    }).then(axios_resp => {
        let d = axios_resp.data;
        dbg("%j", d);
        let href = d['href'];
        dbg("upload href is ", href);
        let parsedHref = url.parse(href);
        let request = https.request({
            method: d['method'],
            hostname: parsedHref.hostname,
            path: parsedHref.path
        }, (httpRes) => {
            console.log("-----");
            dbg("headers-->");
            dbg("%j", httpRes.headers);
            dbg("status code ", httpRes.statusCode, httpRes.statusMessage)
            httpRes.pipe(process.stdout);
        });

        let count = 0;
        let fileRead;
        function transfer2Yandex() {
            count++;
            fileRead = fs.createReadStream(path.join(mntpath, "8WEpS8u4MsZMMETQvtWY5EAX.msi"));
            fileRead.on("data", (chunk) => {
                // dbg("write...");
                process.stderr.write(`[${count}]write..`);
                request.write(chunk);
            });
            fileRead.on("close",()=>{
                dbg(`[${count}]stream end`);
                if(count<10){
                    transfer2Yandex();
                }else{
                    dbg("stream close");
                    request.end(null);
                }
            });
        };
        transfer2Yandex();
    }).catch((axiosFailReason) => {
        dbg(`Fail:${axiosFailReason}`);
    })